package com.choosefine.paycenter.channel.abc.api.impl;

import com.abc.pay.client.Constants;
import com.abc.pay.client.JSON;
import com.abc.pay.client.ebus.PaymentRequest;
import com.choosefine.paycenter.channel.abc.entity.ABCCommodityType;
import com.choosefine.paycenter.channel.abc.entity.ABCPaymentType;
import com.choosefine.paycenter.channel.abc.entity.ABCPayTypeId;
import com.choosefine.paycenter.channel.abc.entity.ABCPaymentRequest;
import com.choosefine.paycenter.common.utils.DateUtil;
import com.choosefine.paycenter.pay.api.AbstractPayService;
import com.choosefine.paycenter.pay.dto.PayOrderDto;
import com.choosefine.paycenter.pay.enums.NotifyType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 潘钱钦
 *         2017下午3:02:15
 *         农行进行充值支付
 */
@Slf4j
@Service("abcPayService")
public class ABCPayServiceImpl extends AbstractPayService {
    @Value("${bank.abc.resultNotifyUrl}")
    private String resultNotifyUrl = null;

    @Override
    public String buildRequest(PayOrderDto payOrderDto, String payType) {
        ABCPaymentRequest abcPaymentRequest = new ABCPaymentRequest();
        try {
            if (ABCPayType.B2C_NB.getType().equals(payType)) {
                abcPaymentRequest.getAbcDicRequest().setPaymentType(ABCPaymentType.ABC_PYAMENT_MERGE_PAY);
                abcPaymentRequest.getAbcDicRequest().setPaymentLinkType(Constants.PAY_LINK_TYPE_NET);
            }else if (ABCPayType.B2B_NB.getType().equals(payType)) {
                abcPaymentRequest.getAbcDicRequest().setPaymentType(ABCPaymentType.ABC_PUBLIC_ACCOUNTS_PAY);
                abcPaymentRequest.getAbcDicRequest().setPaymentLinkType(Constants.PAY_LINK_TYPE_NET);

            } else if (ABCPayType.B2C_APP.getType().equals(payType)) {
                abcPaymentRequest.getAbcDicRequest().setPaymentType(ABCPaymentType.ABC_PYAMENT_MERGE_PAY);
                abcPaymentRequest.getAbcDicRequest().setPaymentLinkType(Constants.PAY_LINK_TYPE_MOBILE);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        abcPaymentRequest.getAbcDicOrder().setOrderNo(payOrderDto.getOrderId());
        BigDecimal bd = payOrderDto.getAmount();
        bd.setScale(2, BigDecimal.ROUND_HALF_UP);
        String orderAmount = bd.toString();
        abcPaymentRequest.getAbcDicOrder().setOrderAmount(orderAmount);
        abcPaymentRequest.getAbcDicRequest().setResultNotifyURL(resultNotifyUrl);//此处设置我们系统的PayCallBackController中的农业银行支付结果服务器通知回调的requestmapping的URL（应为公网）
        String gotoUrl = buildAbcRechargeOrder(abcPaymentRequest);
        return gotoUrl;
    }

    @Override
    public boolean verifySign(Map<String, String> params, String sign, String payType) {
        return false;
    }

    @Override
    public boolean verifySign(Map<String, String> params, String sign, String payType, NotifyType notifyType) {
        return false;
    }

    @Override
    public Map orderInfo(PayOrderDto order) {
        return null;
    }

    @Override
    public PayOrderDto getPayOrderFromBackParam(Map<String, String> params) {
        PayOrderDto payOrderDto = new PayOrderDto(params.get("ORDERID"), BigDecimal.valueOf(Double.valueOf(params.get("PAYMENT"))));
        return payOrderDto;
    }

    @Override
    public void init() {

    }

    /**
     * 生成订单对象
     *
     * @param abcPaymentRequest
     * @return
     */
    public String buildAbcRechargeOrder(ABCPaymentRequest abcPaymentRequest) {
        PaymentRequest tPaymentRequest = new PaymentRequest();
        tPaymentRequest.dicOrder.put("PayTypeID", ABCPayTypeId.ImmediatePay);                   //设定交易类型(直接支付)
        tPaymentRequest.dicOrder.put("OrderDate", DateUtil.getDateEn(new Date()));                  //设定订单日期 （必要信息 - YYYY/MM/DD）
        tPaymentRequest.dicOrder.put("OrderTime", DateUtil.getTime(new Date()));                   //设定订单时间 （必要信息 - HH:MM:SS）
        tPaymentRequest.dicOrder.put("orderTimeoutDate", abcPaymentRequest.getAbcDicOrder().getOrderTimeountDate());     //设定订单有效期
        tPaymentRequest.dicOrder.put("OrderNo", abcPaymentRequest.getAbcDicOrder().getOrderNo());                       //设定订单编号 （必要信息）
        tPaymentRequest.dicOrder.put("CurrencyCode", abcPaymentRequest.getAbcDicOrder().getCurrencyCode());             //设定交易币种
        tPaymentRequest.dicOrder.put("OrderAmount", abcPaymentRequest.getAbcDicOrder().getOrderAmount());      //设定交易金额
        tPaymentRequest.dicOrder.put("Fee", abcPaymentRequest.getAbcDicOrder().getFee());                               //设定手续费金额
        tPaymentRequest.dicOrder.put("AccountNo", abcPaymentRequest.getAbcDicOrder().getAccountNo());                   //设定支付账户
        tPaymentRequest.dicOrder.put("OrderDesc", abcPaymentRequest.getAbcDicOrder().getOrderDesc());                   //设定订单说明
        tPaymentRequest.dicOrder.put("OrderURL", abcPaymentRequest.getAbcDicOrder().getOrderURL());                     //设定订单地址
        tPaymentRequest.dicOrder.put("ReceiverAddress", abcPaymentRequest.getAbcDicOrder().getReceiverAddress());       //收货地址
        tPaymentRequest.dicOrder.put("InstallmentMark", abcPaymentRequest.getAbcDicOrder().getInstallmentMark());       //分期标识
        if (abcPaymentRequest.getAbcDicOrder().getInstallmentMark() == "1" && abcPaymentRequest.getAbcDicOrder().getPayTypeID() == "DividedPay") {
            tPaymentRequest.dicOrder.put("InstallmentCode", abcPaymentRequest.getAbcDicOrder().getInstallmentCode());   //设定分期代码
            tPaymentRequest.dicOrder.put("InstallmentNum", abcPaymentRequest.getAbcDicOrder().getInstallmentNum());     //设定分期期数
        }
        tPaymentRequest.dicOrder.put("CommodityType", ABCCommodityType.ABC_COMMODITY_CONSUME_TRADITION);           //设置商品种类
        tPaymentRequest.dicOrder.put("BuyIP", abcPaymentRequest.getAbcDicOrder().getBuyIP());                           //IP
        tPaymentRequest.dicOrder.put("ExpiredDate", abcPaymentRequest.getAbcDicOrder().getExpiredDate());               //设定订单保存时间
        //2、订单明细
        LinkedHashMap orderitem = new LinkedHashMap();
        orderitem.put("SubMerName", abcPaymentRequest.getAbcOrderitems().getSubMerName());    //设定二级商户名称
        orderitem.put("SubMerId", abcPaymentRequest.getAbcOrderitems().getSubMerId());    //设定二级商户代码
        orderitem.put("SubMerMCC", abcPaymentRequest.getAbcOrderitems().getSubMerMCC());   //设定二级商户MCC码
        orderitem.put("SubMerchantRemarks", abcPaymentRequest.getAbcOrderitems().getSubMerchantRemarks());   //二级商户备注项
        orderitem.put("ProductID", abcPaymentRequest.getAbcOrderitems().getProductID());//商品代码，预留字段
        orderitem.put("ProductName", "施小包-支付订单");//商品名称
        orderitem.put("UnitPrice", abcPaymentRequest.getAbcOrderitems().getUnitPrice());//商品总价
        orderitem.put("Qty", abcPaymentRequest.getAbcOrderitems().getQty());//商品数量
        orderitem.put("ProductRemarks", abcPaymentRequest.getAbcOrderitems().getProductRemarks()); //商品备注项
        orderitem.put("ProductType", abcPaymentRequest.getAbcOrderitems().getProductType());//商品类型
        orderitem.put("ProductDiscount", abcPaymentRequest.getAbcOrderitems().getProductDiscount());//商品折扣
        orderitem.put("ProductExpiredDate", abcPaymentRequest.getAbcOrderitems().getProductExpiredDate());//商品有效期
        tPaymentRequest.orderitems.put(1, orderitem);

        //3、生成支付请求对象
        String paymentType = abcPaymentRequest.getAbcDicRequest().getPaymentType();
        tPaymentRequest.dicRequest.put("PaymentType", paymentType);            //设定支付类型
        String paymentLinkType = abcPaymentRequest.getAbcDicRequest().getPaymentLinkType();
        tPaymentRequest.dicRequest.put("PaymentLinkType", paymentLinkType);    //设定支付接入方式
        if (paymentType.equals(Constants.PAY_TYPE_UCBP) && paymentLinkType.equals(Constants.PAY_LINK_TYPE_MOBILE)) {
            tPaymentRequest.dicRequest.put("UnionPayLinkType", abcPaymentRequest.getAbcDicRequest().getUnionPayLinkType());  //当支付类型为6，支付接入方式为2的条件满足时，需要设置银联跨行移动支付接入方式
        }
        tPaymentRequest.dicRequest.put("ReceiveAccount", abcPaymentRequest.getAbcDicRequest().getReceiveAccount());      //设定收款方账号
        tPaymentRequest.dicRequest.put("ReceiveAccName", abcPaymentRequest.getAbcDicRequest().getReceiveAccName());      //设定收款方户名
        tPaymentRequest.dicRequest.put("NotifyType", Constants.NOTIFY_TYPE_SERVER);              //设定通知方式(默认为服务器通知)
        tPaymentRequest.dicRequest.put("ResultNotifyURL", abcPaymentRequest.getAbcDicRequest().getResultNotifyURL());    //设定通知URL地址
        tPaymentRequest.dicRequest.put("MerchantRemarks", "充值");    //设定附言
        tPaymentRequest.dicRequest.put("IsBreakAccount", "0"); //设定交易是否分账(默认为不分账)
        tPaymentRequest.dicRequest.put("SplitAccTemplate", abcPaymentRequest.getAbcDicRequest().getSplitAccTemplate());  //分账模版编号

        System.out.println(tPaymentRequest.dicRequest.get("PaymentLinkType"));
        JSON json = tPaymentRequest.postRequest();
        //JSON json = tPaymentRequest.extendPostRequest(1);

        String ReturnCode = json.GetKeyValue("ReturnCode");
        String ErrorMessage = json.GetKeyValue("ErrorMessage");
        if (ReturnCode.equals("0000")) {
            log.info("ReturnCode   = [" + ReturnCode + "]");
            log.info("ErrorMessage = [" + ErrorMessage + "]");
            log.info("PaymentURL-->" + json.GetKeyValue("PaymentURL"));
            return json.GetKeyValue("PaymentURL");
        } else {
            return ErrorMessage;
        }
    }
}
